package com.fund.client.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fund.client.mapper.ClientMapper;
import com.fund.client.pojo.dto.ClientPageDTO;
import com.fund.client.pojo.dto.Questionnaire;
import com.fund.client.pojo.entity.Client;
import com.fund.client.pojo.vo.ClientVO;
import com.fund.client.service.ClientService;
import com.fund.client.utils.AccountCodeGenerator;
import com.fund.common.enums.ClientStatus;
import com.fund.common.pojo.PageResult;
import com.fund.common.pojo.Result;
import com.fund.common.utils.UserContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ClientServiceImpl extends ServiceImpl<ClientMapper, Client> implements ClientService {

    @Autowired
    StringRedisTemplate stringRedisTemplate;


    /**
     * 开户
     * @param client
     * @return
     */
    @Override
    public Result<Boolean> openAccount(Client client) {
        Long userId = UserContext.getUser();
        //判断是开户还是修改
        //若是新增
        if(client.getId() == null){
            //生成账户代码
            String code = new AccountCodeGenerator(stringRedisTemplate).getNewAccountCode();
            client.setAccountNumber(code);
            client.setCreateUser(userId);
            client.setUpdateUser(userId);
            client.setCreateTime(LocalDateTime.now());
            client.setUpdateTime(LocalDateTime.now());
            client.setStatus(ClientStatus.FROZEN);
            return Result.success(save(client));
        }
        //若是修改
        client.setUpdateTime(LocalDateTime.now());
        client.setUpdateUser(userId);
        return Result.success(updateById(client));
    }

    @Override
    public Result<PageResult<ClientVO>> getPage(ClientPageDTO clientPageDTO) {
        //判断分页参数是否正确
        if(clientPageDTO.getCurrentPage() <= 0 || clientPageDTO.getPageSize() <= 0){
            return Result.fail("分页参数错误");
        }

        //构建查询参数
        QueryWrapper<Client> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .likeRight(clientPageDTO.getName() != null, Client::getName, clientPageDTO.getName())
                .likeRight(clientPageDTO.getAccountNumber() != null, Client::getAccountNumber, clientPageDTO.getAccountNumber())
                .eq(clientPageDTO.getStatus() != null, Client::getStatus, clientPageDTO.getStatus())
                .eq(clientPageDTO.getType() != null, Client::getType, clientPageDTO.getType())
                .eq(clientPageDTO.getRiskTolerance() != null, Client::getRiskTolerance, clientPageDTO.getRiskTolerance())
                .eq(clientPageDTO.getTarget() != null, Client::getTarget, clientPageDTO.getTarget());
        //分页
        IPage<Client> page = new Page<>(clientPageDTO.getCurrentPage(), clientPageDTO.getPageSize());

        //查询
        IPage<Client> clientIPage = page(page, queryWrapper);
        //为空直接返回
        if(clientIPage.getRecords() == null || clientIPage.getRecords().isEmpty()){
            return Result.success(new PageResult<>(page.getTotal(),new ArrayList<>()));
        }
        //转化VO
        List<ClientVO> clientVOS = new ArrayList<>();
        System.out.println(clientIPage.getTotal()+" "+clientIPage.getPages());
        for(Client client : clientIPage.getRecords()){
            ClientVO clientVO = new ClientVO();
            BeanUtils.copyProperties(client, clientVO);
            clientVOS.add(clientVO);
        }
        //返回
        return Result.success(new PageResult<>(clientIPage.getTotal(),clientVOS));
    }

    /**
     * 填写风险承受能力测评问卷
     * @param questionnaire
     * @return
     */
    @Override
    public Result<Boolean> fillQuestionnaire(Questionnaire questionnaire) {
        //确认传递id
        if(questionnaire.getId() == null){
            return Result.fail("没有指定填写问卷的客户");
        }
        //填写问卷
        Client client = new Client();
        BeanUtils.copyProperties(questionnaire, client);
        //更新填写问卷的时间
        client.setQuestionnaireTime(LocalDateTime.now());
        //填写完风险测评问卷，将客户状态设为正常
        client.setStatus(ClientStatus.NORMAL);
        return Result.success(updateById(client));
    }

    /**
     * 客户账号模糊查询
     * @param clientQuery
     * @return
     */
    @Override
    public Result<List<ClientVO>> findByCode(String clientQuery) {
        //只返回前五个
        IPage<Client> page = new Page<>(1,5);
        //查询
        List<Client> clients = lambdaQuery().
                likeRight(clientQuery != null, Client::getAccountNumber, clientQuery)
                .page(page).getRecords();
        //转化为vo返回
        List<ClientVO> clientVOS = new ArrayList<>();
        for(Client client : clients){
            ClientVO clientVO = new ClientVO();
            BeanUtils.copyProperties(client, clientVO);
            clientVOS.add(clientVO);
        }
        return Result.success(clientVOS);
    }

    @Override
    public Result<ClientVO> findById(Long id) {
        //查询
        Client client = getById(id);
        //转化为vo返回
        ClientVO clientVO = new ClientVO();
        BeanUtils.copyProperties(client, clientVO);
        return Result.success(clientVO);
    }
}
